package me.lijf.xapi.controller;

import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import me.lijf.xapi.dto.RestResponse;
import me.lijf.xapi.entity.User;
import me.lijf.xapi.exception.XException;
import me.lijf.xapi.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {
    @Autowired
    UserServiceImpl userService;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private ObjectMapper mapper;

    @PostMapping("/register")
    public RestResponse register(@RequestBody User form) throws JsonProcessingException {
        if(userService.save(form))
            return RestResponse.success(null);
        throw new XException(500,"注册失败");
    }

    @PostMapping("/login")
    public RestResponse login(@RequestBody User form) throws JsonProcessingException {
        QueryWrapper<User> parmas= new QueryWrapper<User>();
        parmas.eq("name",form.getName()).eq("password",form.getPassword());
        User user=userService.getOne(parmas);
        if(user==null) throw new XException(403,"账户或密码错误");
        String token=mapper.writeValueAsString(user);
        String key=String.valueOf(MD5.create().digest(token));
        redisTemplate.boundValueOps("token::"+key).set(token);
        redisTemplate.boundValueOps("token::"+key).expire(1l, TimeUnit.HOURS);
        Object value=redisTemplate.boundValueOps("token::"+key).get();
        if(value==null) throw new XException(404,"未缓存请求的数据");
        Map<String,Object> result=new HashMap<>();
        result.put("user",user);
        result.put("token",key);
        return RestResponse.success(result);
    }
}
